package com.xiaolin.shiro.service;

import com.xiaolin.shiro.model.Member;
import com.xiaolin.shiro.model.Permission;
import com.xiaolin.shiro.model.Role;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @ClassName CustomRealm
 * @Description Realm
 * @Detail 负责校验用户身份和授权
 * @Author MyPC
 * @Date 2020/10/11
 * @Version 1.0
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    LoginService loginService;

    /**
     * 授权配置类-给认证通过的用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户输入的用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        Member member = loginService.getMemberByName(name);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : member.getRoles()) {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            for (Permission permission : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permission.getPermission());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证配置,证明用户身份
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if(StringUtils.isEmpty(authenticationToken.getPrincipal())){
            return null;
        }
        //获取用户名
        String name = authenticationToken.getPrincipal().toString();
        //获取用户名
        Member member = loginService.getMemberByName(name);
        if(member == null){
            //返回空会抛出异常
            return null;
        }
        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        System.out.println(getName());
        return new SimpleAuthenticationInfo(name, member.getPassword(), getName());
    }

}
